package com.noahedu.style.html2;

import java.io.IOException;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.text.style.ReplacementSpan;

import com.noahedu.style.R;
import com.noahedu.style.ui.StyleApplication;

/**
 * 这个类的作用是在文本加背景色
 * 和DangBanSpan6使用
 * 
 * 和BackgroundColorSpan 区别在于行间有一定距离
 * 对应标签
 * 
 * <back3>word</back3> 20120625
 */
public class BackColorSpan7 extends ReplacementSpan
{

	private static final String TAG = "BackColorSpan7"; 

	/**
	 * 
	 */
	public final static int STATE_TRANSPARENT  =0 ; //画透明色 ，也可以不画
	public final static int STATE_BEGIN  =1 ; 
	public final static int STATE_MID = 2 ; 
	public final static int STATE_END = 3 ;
	//跨行下只有一个词汇用
	public final static int STATE_ONE_WORD = 4 ;
	
	
	/**
	 * 根据该值绘制 不同图片
	 */
	private int mstate;
	
	
//	/**
//	 * 文字两侧的
//	 */
//	private float mTextOffset;
//	/**
//	 * 拼音最外侧两侧
//	 */
//	private float mNoteOffset;
	
	
//	/**
//	 * 最外侧
//	 */
//	private int mPadding; // left and right padding

	
	/**
	 * .9图片资源
	 */
	private static BitmapDrawable drawbitmap_mid;
	private static BitmapDrawable drawbitmap_end;
	private static BitmapDrawable drawbitmap_begin;

	/**
	 * 该样式宽度
	 */
	private int mWid = -1;

	private NinePatch np_begin;

	private NinePatch npEnd;

	private NinePatch np_mid;

	/**
	 * 测量宽度，保存
	 */
	private int mMeasureWid = - 1 ;

	/**
	 * 
	 * @param tcolor
	 *            外部保证有效性
	 */
	public BackColorSpan7(int tstate)
	{
		
		mstate = tstate ;
	}

	
	public BackColorSpan7()
	{
		
		mstate = STATE_MID ;
	}
	
	/**
	 * 不同state ，绘制图片不同
	 * 
	 * 1 ==== begin（左边）
	 * 2 === mid 
	 * 3 ==== end(右边)
	 */
	public void setState( int  tstate){
		mstate = tstate;
	}
	
	/**
	 * 20120627
	 * text ===全部内容  textview
	 * 
	 * 
	 */
	@Override
	public void draw(Canvas canvas, CharSequence text, int start, int end,
			float x, int top, int y, int bottom, Paint paint)
	{

//		Log.i("test_debug", TAG+ "----draw+======="+mstate);
		
		// 加颜色后行间空隙来自属性
		// canvas.save();
		// int w = getWid(text, start, end, paint);
		// canvas.clipRect(x, y+paint.ascent(), x+w, y+
		// // paint.getFontSpacing());
		// canvas.clipRect(x, y, x+w, y+paint.getFontSpacing());
		// canvas.drawColor(Color.YELLOW);
		// canvas.restore();

		// 汉字来自标签内容
		// canvas.drawText(text, start, end, x + mTextOffset, y, paint);
		//20120627 优化屏蔽		
		canvas.drawText(text, start, end, x, y, paint);

		
		if(mWid <0){
			mWid = getWid(text, start, end, paint);
		}

		canvas.save();
		
		// // canvas.clipRect(x, y+paint.ascent(), x+w, y+
		// paint.getFontSpacing());
//		float t = 0;
//		t = paint.getFontMetrics().leading;
//		t = paint.getFontMetrics().top;
//		t = paint.getFontMetrics().bottom;
//		t = paint.getFontMetrics().ascent;
//		t = paint.getFontMetrics().descent;

		// canvas.clipRect(x, y-paint.getFontSpacing() , x+w+ 4, y+2);
		canvas.clipRect(x, y + paint.getFontMetrics().ascent, x + mWid, y
				+ paint.getFontMetrics().descent);
		// 指定颜色
		// canvas.drawColor(mColor);
		
	
		 
		
		//test 20120624
		getMidpic(mstate);	

		if(mstate == STATE_TRANSPARENT){
			
          //这行代码有问题！！！Log.v(TAG, "draw: " + text.subSequence(start, end).toString());
			
			//透明白色
//			Log.v(TAG, "draw-------------------------");
//			canvas.drawColor(Color.parseColor("#00FFFFFF"));
			

		}else if(mstate == STATE_BEGIN){
			if(np_begin == null){
				 Bitmap bitmap = drawbitmap_begin.getBitmap();
				 byte[] chunk = bitmap.getNinePatchChunk();
				 np_begin = new NinePatch(bitmap, chunk, null);
			}
		   
			Rect location = new Rect((int) x,
					(int) (y + paint.getFontMetrics().ascent), (int) (x + mWid),
					(int) (y + paint.getFontMetrics().descent));
			np_begin.draw(canvas, location);
			
		}else if(mstate == STATE_END){
			
			if( npEnd == null){
				Bitmap bitmap = drawbitmap_end.getBitmap();
				byte[] chunk = bitmap.getNinePatchChunk();
				npEnd = new NinePatch(bitmap, chunk, null);
			}
			
			Rect location = new Rect((int) x,
					(int) (y + paint.getFontMetrics().ascent), (int) (x + mWid),
					(int) (y + paint.getFontMetrics().descent));
			npEnd.draw(canvas, location);
			
		}else{
			
			if(np_mid == null){
				Bitmap bitmap = drawbitmap_mid.getBitmap();
				byte[] chunk = bitmap.getNinePatchChunk();
				np_mid = new NinePatch(bitmap, chunk, null);
			}

//			Rect location = new Rect((int) x,
//					(int) (y + paint.getFontMetrics().ascent), (int) (x + mWid),
//					(int) (y + paint.getFontMetrics().descent));
			
			
			//20120702 ,英文g字母挡板不能全挡住
			//float 转 int 丢失了准度
			Rect location = new Rect((int) Math.ceil(x),
					(int)  Math.ceil(y + paint.getFontMetrics().ascent), (int)  Math.ceil(x + mWid),
					(int)  Math.ceil(y + paint.getFontMetrics().descent));
			
			//测试暂时修改ttt
//			Rect location = new Rect((int) x+2,
//					(int) (y + paint.getFontMetrics().ascent)+2, (int) (x + w)-2,
//					(int) (y + paint.getFontMetrics().descent)-2 );
			
			np_mid.draw(canvas, location);
		}

		
		
		//20120624 ，不能回收回收
//		bitmap.recycle();
		
		canvas.restore();

	}


	/**
	 * 获取图片
	 * 
	 */
	private void getMidpic(int state )
	{
		//中间图片
		if (state == STATE_MID && drawbitmap_mid == null)
		{
			Resources resources = StyleApplication.getInstance()
					.getResources();
			InputStream inputStream = resources
					.openRawResource(R.drawable.dang_mid9);
			drawbitmap_mid = new BitmapDrawable(resources, inputStream);

			//读取
			if (inputStream != null)
			{
				try
				{
					inputStream.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		
//		//图片
//		if (state == STATE_BEGIN  && drawbitmap_begin == null)
//		{
//			Resources resources = StyleApplication.getInstance()
//					.getResources();
//			InputStream inputStream = resources
//					.openRawResource(R.drawable.dang_begin9);
//			drawbitmap_begin = new BitmapDrawable(resources, inputStream);
//
//			//读取
//			if (inputStream != null)
//			{
//				try
//				{
//					inputStream.close();
//				}
//				catch (IOException e)
//				{
//					e.printStackTrace();
//				}
//			}
//		}
//		
//		
//		//图片
//		if (state == STATE_END  && drawbitmap_end == null)
//		{
//			Resources resources = StyleApplication.getInstance()
//					.getResources();
//			InputStream inputStream = resources
//					.openRawResource(R.drawable.dang_end9);
//			drawbitmap_end = new BitmapDrawable(resources, inputStream);
//
//			//读取
//			if (inputStream != null)
//			{
//				try
//				{
//					inputStream.close();
//				}
//				catch (IOException e)
//				{
//					e.printStackTrace();
//				}
//			}
//		}
		
		
		
	}
	
	
    /**
     * 获得该样式部分内容宽度    
     * 
     *@param text
     *@param start
     *@param end
     *@param paint
     *@return
     */
	private int getWid(CharSequence text, int start, int end, Paint paint)
	{
		//
//		int tWidth = 0;
//		float[] textw = new float[end - start];
//		paint.getTextWidths(text, start, end, textw);
//		for (int i = 0; i < textw.length; i++)
//		{
//			tWidth += textw[0];
//		}
		
		//方法111
//		return  tWidth;
		
		///方法222222
		String str = text.toString();
		int wid_totol = (int) paint.measureText(str.substring(start, end));

		return wid_totol;
	}



	@Override
	public int getSize(Paint paint, CharSequence text, int start, int end,
			FontMetricsInt fm)
	{
//		Log.v(TAG, "getSize-------------------------");
		
		if(mMeasureWid >0){
			//如果已经测量
			return mMeasureWid;
		}
		
		
		// 测量标签内容
		float[] textw = new float[end - start];
		paint.getTextWidths(text, start, end, textw);

		// Rect bounds = new Rect();
		// mPaint.getTextBounds(text, 0, text.length(), bounds);
		// text.subSequence(start, end);//*******/////////

		// 改写，空隙
		float[] pinyinw = new float[1];
		// if (mNote != null) {
		// pinyinw = new float[mNote.length()];
		// paint.getTextWidths(mNote, 0, mNote.length(), pinyinw);
		// }

		float tw = 0f;
		float pw = 0f;
		for (float i : textw)
		{
			tw += i;
		}
		for (float j : pinyinw)
		{
			pw += j;
		}
		
		

		mMeasureWid = (int) Math.ceil(Math.max(tw, pw));

		if (fm != null)
		{
			/*20120810 ,调整这里字体设置有助消除这个现象
			 * 0178470: V1.0.3 苏教-语文-六年级-上学期，第9课《小草和大树》【背会了】和【录音】界面，文章第一行有一半文字未显示，请修改。
			 */
//			fm.ascent = -(int) ((int) paint.getFontSpacing() * (0.5));
			fm.ascent = -(int) ((int) paint.getFontSpacing() * (0.7));

			fm.descent = 0;
			// fm.leading
			
//			fm.top = fm.ascent - 2;
			fm.top = fm.ascent - 5;
			fm.bottom = 0;
		}

		return mMeasureWid;
	}
}
